package mysql

import (
	"bluebell/models"
	"bluebell/utils"
	"crypto/md5"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

//CheckUserExist  检查是否存在用户
func CheckUserExist(userName string) (err error, isExist bool) {
	var user models.User
	res := DB.Where("username=?", userName).First(&user)
	if err = res.Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, false
		} else {
			return err, false
		}
	}
	if res.RowsAffected > 0 {
		return nil, true
	} else {
		return nil, false
	}

}

// InsertUser  插入用户数据
func InsertUser(user *models.User) (err error) {
	//1、加密密码
	user.Password = encryptPassword(user.Password)
	//2、插入数据库
	if err = DB.Create(user).Error; err != nil {
		return
	}
	return
}

//VerifyAccount 验证登录用户的用户名和密码是否正确(先查用户名是否存在，再查密码是否正确,最后返回用户ID)
func VerifyAccount(loginUser *models.ParamLogin) (err error, userid uint) {
	var u models.User
	if err = DB.Where(&models.ParamLogin{
		Username: loginUser.Username,
	}).Take(&u).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return utils.ErrorUserNotExist, 0
		} else {
			return err, 0
		}
	} else {
		if err = DB.Where(&models.User{
			Username: loginUser.Username,
			Password: encryptPassword(loginUser.Password),
		}).Take(&u).Error; err != nil {
			return utils.ErrorInvalidPassword, 0
		} else {
			return nil, u.Model.ID
		}

	}

}

// encryptPassword  md5加密密码
func encryptPassword(originPassword string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(originPassword)))
}
